/* Kenneth Moore 9%25%03 file to show operator overloading. side by side comparison of Abstract Data Type complex provided in C++ with my version kplex. */ #include #include using namespace std; class kplex{ private: int r,i; public: // constructors kplex():r(0),i(0){} kplex(int a, int b):r(a),i(b){} // accessors int getr(){return r;} int geti(){return i;} // copy constructor kplex(kplex &knew){ i = knew.geti(); r = knew.getr(); cout << "in copy constructor" << endl; } // mutator void seti(int x){i = x;} // // operator overloads // // + overload const kplex operator+(kplex m){ // for return, construct an anonymous variable return kplex(r+m.getr(),i+m.geti()); } // << overload friend ostream& operator<<(ostream& co, kplex w); }; ostream& operator<<(ostream& co, kplex w){ co << "[" << w.getr() << " + i" << w.geti() << "]" << endl; return co; } void main(){ // // show how the ADT complex operates // complex a(1,1), b(2,2),c; c = a+b; cout << c << endl; // // show how kplex operates // kplex p(1,1), q(2,2), r; //(p+q).seti(42); would be allowed if + returned non-const r = p + q; cout << p << endl; // not changed cout << r << endl; // result of adding p and q }